package com.googlecode.roleaccesscontrol.uc.user;

import java.util.Iterator;

import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;

import com.googlecode.roleaccesscontrol.entity.User;

public class UserDataProvider extends SortableDataProvider<User> {

	private UserRepository userRepository;
	private UserFilter filter;

	public UserDataProvider(UserRepository userRepository) {
		this.userRepository = userRepository;
	}

	public Iterator<? extends User> iterator(int first, int count) {
		String sortProperty = null;
		boolean asc = true;
		if (getSort() != null) {
			sortProperty = getSort().getProperty();
			asc = getSort().isAscending();
		}

		return userRepository.listUsers(filter, first, count, sortProperty, asc).iterator();
	}

	public IModel<User> model(User user) {
		return new LoadableDetachableUserModel(user);
	}

	public int size() {
		return userRepository.count(filter);
	}

	private class LoadableDetachableUserModel extends LoadableDetachableModel<User> {
		private Long id;

		public LoadableDetachableUserModel(User user) {
			this.id = user.getId();
		}

		@Override
		protected User load() {
			return userRepository.getById(id);
		}
	}

	public void setFilterParameters(UserFilter filter) {
		this.filter = filter;
	}
}
